// pages/login/login.js
const app = getApp();
const storage = require('../../utils/storage');
const util = require('../../utils/util');
const api = require('../../utils/api');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // 软键盘高度
    keywordHeight: 300,
    // 当前登录方式
    loginStatus: 2, // 1:微信登陆，2:密码登陆，3、手机登陆
    // 头部标题
    headerTitle: '登录',
    code: null,
    isWechatPopShow: false,
    phoneNumber: null,
    codeInfo: false,
    codeTime: 30
  },
  onLoad: function (options) {
    
  },
  // 选择登陆方式
  loginType(e){
    this.setData({
      loginStatus: e.currentTarget.dataset.loginstatus
    })
  },
  
  // 关闭微信登陆弹窗
  closeWechatPop(){
    this.setData({
      isWechatPopShow: false
    })
  },
  // 获取手机号
  getPhoneFocus:function(e){
    this.setData({
     phoneNumber: e.detail.value
    })
   },
  
  // 去注册
  jumpToRegister:function(){
    wx.reLaunch({
      url: '/pages/register/register',
    })
  },
  // 获取手机号
  getPhoneFocus:function(e){
    this.setData({
     phoneNumber: e.detail.value
    })
   },
   // 获取手机验证码
  getPhoneCode:function(e){
    let that = this;
    if(util.checkEmpty(this.data.phoneNumber)){
      wx.showToast({
        title: '手机号不能为空！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(!util.checkPhone(this.data.phoneNumber)){
      wx.showToast({
        title: '手机号不正确！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    api.getPhoneCode(this.data.phoneNumber).then(res => {
      if(res.code == 0){
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
        let n = 30;
        let timer = setInterval(function(){
          n--;
          that.setData({
            codeInfo: true,
            codeTime: n--
          })
          if(n<=0){
            clearInterval(timer);
            that.setData({
              codeInfo: false,
              codeTime: null
            })
          }
        },1000)
      }
    })
  },
  // 微信登陆(是否第一次登陆)
  wechatLogin:function(){
    let that = this
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if(res.code && res.code != ''){
          that.setData({
            code: res.code
          })
          api.wechatLogin({code:res.code}).then(res => {
            if(res.code == 0){
              that.loginSuccess(res.data)
            }else{
              that.setData({
                isWechatPopShow: true
              })
            }
          }).catch(e => {
            console.info(e)
          })
        }
      },
      fail:res => {
      }
    })
  },
  // 微信授权登录(唤起手机号授权)
  getPhoneNumber:function(e){
    let that = this
    let wechatLoginOption = {}
    if (e.detail.errMsg == "getPhoneNumber:ok"){
      wechatLoginOption.encryptedData = e.detail.encryptedData
      wechatLoginOption.iv = e.detail.iv
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if(res.code && res.code != ''){
            wechatLoginOption.code = res.code
            // 获取用户信息
            wx.getUserInfo({
              success: function (res) {
                wechatLoginOption.nick_name = res.userInfo.nickName
                wechatLoginOption.avatar_url = res.userInfo.avatarUrl
                api.wechatLogin(wechatLoginOption).then(res => {
                console.info(res)
                if(res.code == 0){
                  that.loginSuccess(res.data)
                }else{
                  wx.showToast({
                    title: res.msg,
                  })
                }
                this.setData({
                  isWechatPopShow: false
                })
              }).catch(e => {
                console.info(e)
              })
            },
            })
          }
        },
        fail:res => {
        }
      })
    }
  },
  // 账号密码登录提交
  passwordLoginSubmit(e){
    let that = this
    if(util.checkEmpty(e.detail.value.phone)){
      wx.showToast({
        title: '账号不能为空！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(!util.checkPhone(e.detail.value.phone)){
      wx.showToast({
        title: '手机号不正确！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(util.checkEmpty(e.detail.value.password)){
      wx.showToast({
        title: '密码不能为空！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    api.login({identifier:e.detail.value.phone,credential:e.detail.value.password}).then(res => {
      console.info(res)
      if(res.code == 0){
        that.loginSuccess(res.data)
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  // 手机验证码登陆
  phoneLoginSubmit(e){
    if(util.checkEmpty(e.detail.value.phone)){
      wx.showToast({
        title: '手机号不能为空！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(!util.checkPhone(e.detail.value.phone)){
      wx.showToast({
        title: '手机号不正确！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(util.checkEmpty(e.detail.value.code)){
      wx.showToast({
        title: '验证码不能为空！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    api.phoneLogin({mobile:e.detail.value.phone,code:e.detail.value.code}).then(res => {
      console.info(res)
      if(res.code == 0){
        that.loginSuccess(res.data)
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  // 登陆后是否实名认证
  loginSuccess:function(res){
    storage.setJwtToken(res.token)
    storage.setUserId(res.user.user_id)
    wx.reLaunch({
      url: '/pages/index/index',
    })
    // if(real_name == 0){
    //   wx.reLaunch({
    //     url: '/pages/authentication/authentication',
    //   })
    // }else{
    //   wx.reLaunch({
    //     url: '/pages/index/index',
    //   })
    // }
  }
})